import { _decorator, Camera, Component, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('PlayerCamera')
export class PlayerCamera extends Component {
    @property(Node) player: Node = null;
    @property(Camera) camera: Camera = null;
    private _ratio: number = 0.2;//相机缩放倍率
    private _thresholdHeight: number = 500;//主角开始影响相机高度的阈值
    private _pos: Vec3;
    private _lerpRatio: number = 0.2; // 插值范围，可通过接口修改
    start() {
        this._pos = new Vec3();
    }

    // update(deltaTime: number) {
    //     this.player.getPosition(this._pos);
    //     this._pos.z = 1000;
    //     if(this._pos.y >= this._thresholdHeight){
    //         let offsetY = this._pos.y - this._thresholdHeight;
    //         let h = 1080 + offsetY * this._ratio;
    //         let orthoHeight = Math.min(2160, Math.max(1080, h));
    //         this.camera.orthoHeight = orthoHeight;
    //     }

    //     let posY = Math.max(200, this._pos.y);
    //     this._pos.y = posY;
    //     this.node.setPosition(this._pos);
    // }

    update(deltaTime: number) {
        let targetPos = new Vec3();
        this.player.getPosition(targetPos);
        targetPos.z = 1000;

        if (targetPos.y >= this._thresholdHeight) {
            let offsetY = targetPos.y - this._thresholdHeight;
            let h = 1080 + offsetY * this._ratio;
            let orthoHeight = Math.min(2160, Math.max(1080, h));
            this.camera.orthoHeight = orthoHeight;
        }

        let posY = Math.max(200, targetPos.y);
        targetPos.y = posY;

        // 使用线性插值平滑跟随
        Vec3.lerp(this._pos, this._pos, targetPos, this._lerpRatio);
        this.node.setPosition(this._pos);
    }
}


